
from rest_framework import serializers




def jwt_response_payload_handler(token,user=None, requeset=None):
    return {
        'token':token,
        'username':user.username,
        'id':user.id
    }

from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from django.contrib.auth import authenticate
from django.utils.translation import ugettext as _
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class MeiduoTokenSerializer(JSONWebTokenSerializer):
    def validate(self,attrs):
        credentials = {
            self.username_field: attrs.get(self.username_field),
            'password': attrs.get('password')
        }

        if all(credentials.values()):
            user = authenticate(**credentials)

            if user:
                if not user.is_active:
                    msg = _('User account is disabled.')
                    raise serializers.ValidationError(msg)
                ##################################################
                if not user.is_staff:
                    msg = _('User account is disabled.')
                    raise serializers.ValidationError(msg)
                ################################################
                payload = jwt_payload_handler(user)

                return {
                    'token': jwt_encode_handler(payload),
                    'user': user
                }
            else:
                msg = _('Unable to log in with provided credentials.')
                raise serializers.ValidationError(msg)
        else:
            msg = _('Must include "{username_field}" and "password".')
            msg = msg.format(username_field=self.username_field)
            raise serializers.ValidationError(msg)


#########################
from rest_framework_jwt.views import JSONWebTokenAPIView

class MeiduoObtainJSONWebToken(JSONWebTokenAPIView):

    serializer_class=MeiduoTokenSerializer


meiduo_token = MeiduoObtainJSONWebToken.as_view()


from apps.admin.serializers.user import UserSerializer
from rest_framework.generics import ListAPIView,ListCreateAPIView
from apps.users.models import User
# from rest_framework.pagination import PageNumberPagination
# from rest_framework.response import Response
# from collections import OrderedDict
from apps.admin.utils import PageNum



class UserAPIView(ListCreateAPIView):
    # queryset = User.objects.all().order_by('id')
    def get_queryset(self):
        keyword=self.request.query_params.get('keyword')
        if keyword:
            return User.objects.filter(username__contains=keyword).order_by('id')
        return User.objects.all().order_by('id')

    serializer_class = UserSerializer
    pagination_class = PageNum


